package com.hzmg.akka;

import akka.actor.ActorSelection;
import akka.actor.ActorSystem;
import akka.actor.Props;
import com.google.common.collect.Maps;
import com.hzmg.akka.utils.NetUtils;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Map;

@Slf4j
@Component
public class ActorSystemDemo {
    @Getter
    private static String actorSystemAddress;
    public static  void createActorSystem() {
        //加载resources里的配置文件，里面包含AcotrSystem创建所需参数，
        //设置工作端口，序列化方式，日志级别
        Map<String, Object> overrideConfig = Maps.newHashMap();
        String localIP = NetUtils.getLocalHost();
        overrideConfig.put("akka.remote.artery.canonical.hostname", localIP);
        overrideConfig.put("akka.remote.artery.canonical.port", "10086");
        actorSystemAddress = localIP + ":" + "10086";
        log.info("[AkkaDemo] akka-remote server address: {}", actorSystemAddress);
        Config akkaBasicConfig = ConfigFactory.load("hzmg-server.akka.conf");
        Config akkaFinalConfig = ConfigFactory.parseMap(overrideConfig).withFallback(akkaBasicConfig);

        //创建Actor工厂
        ActorSystem actorSystem = ActorSystem.create("akka-server", akkaFinalConfig);
        //通过Actor工厂创建Actor,
        // 第一个参数为创建Actor时指定选项的配置类,第二个参数指定该Actor的名称，
        //通过该Actor名称与ActorSystem名称，
        //可以构建出路径: akka://hzmg-server/ip/friend_actor，
        //根据该路径找到actor进行通信
        //这种方式适用于远程调用
        actorSystem.actorOf(Props.create(FriendActor.class), "friend_actor");
        //开始通信
        //String actorPath = "akka://akka-server@172.31.160.1:10086/user/friend_actor";
        String actorPath = "akka://remote-call@172.31.160.1:10087/user/friend";
        ActorSelection actorSelection = actorSystem.actorSelection(actorPath);
        actorSelection.tell(actorPath, null);
        log.info("通信发送成功");
    }
public static void main(String[] args){
    createActorSystem();
}

}
